import datetime
from concurrent.futures.thread import ThreadPoolExecutor

from django.conf import settings
from django.http import HttpResponse, JsonResponse
# 表单
from django.views.decorators.csrf import csrf_exempt
import os
from .yolo import cvCNNImage
from .authUtil import auth

from DemoAIServer.requestImagetil import read_image,saveImage
from concurrent.futures import ThreadPoolExecutor, wait, FIRST_COMPLETED, ALL_COMPLETED,as_completed

@csrf_exempt
def yoloForm(request):
    errormes = {'status': 2000}
    if auth(request):
        return JsonResponse(errormes)
    f = request.FILES['image'] #用于保存图片
    image_to_read = read_image(stream=f)
    start = datetime.datetime.now()
    cvcnn=cvCNNImage()
    cvcnn.testClsId()
    with ThreadPoolExecutor(max_workers=2) as t:
        # 线程保存图片
        task1 = t.submit(saveImage, f)  # ,参数
        # 图像识别服务
        task2 = t.submit(cvcnn, image_to_read)
        all_task = [task1, task2]
        for future in as_completed(all_task):
            if future == task2:
                resData = future.result()
    end = datetime.datetime.now()
    print(end - start, flush=True)
    return JsonResponse(resData,safe=False)
